// pkg/logging.go - 日志记录模块
package pkg

import (
	"fmt"
	"log"
	"strings"
	"time"
)

// logResult 记录执行结果到数据库
// func (rct *RemoteControlTool) logResult(result TaskResult) {
// 	stmt, err := rct.DB.Prepare("INSERT INTO logs (ip, command, output, error, success) VALUES (?, ?, ?, ?, ?)")
// 	if err != nil {
// 		log.Printf("准备日志语句失败: %v", err)
// 		return
// 	}
// 	defer stmt.Close()

// 	_, err = stmt.Exec(result.IP, result.Command, result.Output, result.Error, result.Success)
// 	if err != nil {
// 		log.Printf("记录日志失败: %v", err)
// 	}
// }

// logToFile 记录执行结果到文件
func (rct *RemoteControlTool) logToFile(result TaskResult) {
	if len(result.Error) == 0 {
		logEntry := fmt.Sprintf("[%s] IP: %s | Command: %s | Success: %t | Output:\n %s\n\n",
			result.Timestamp, result.IP, result.Command, result.Success, result.Output)
		_, err := rct.LogFile.WriteString(logEntry)
		if err != nil {
			log.Printf("写入日志文件失败: %v", err)
		}
	} else {
		logEntry := fmt.Sprintf("[%s] IP: %s | Command: %s | Success: %t | Output:\n %s | Error: %s\n\n",
			result.Timestamp, result.IP, result.Command, result.Success, result.Output, result.Error)
		_, err := rct.LogFile.WriteString(logEntry)
		if err != nil {
			log.Printf("写入日志文件失败: %v", err)
		}
	}
	
	// _, err := rct.LogFile.WriteString(logEntry)
	// if err != nil {
	// 	log.Printf("写入日志文件失败: %v", err)
	// }
	rct.LogFile.Sync()
}

// logSummaryToFile 记录执行汇总日志
func (rct *RemoteControlTool) logSummaryToFile(results []TaskResult, command string, useRoot bool) {
	if len(results) == 0 {
		return
	}

	failedCount := 0
	for _, result := range results {
		if !result.Success {
			failedCount++
		}
	}

	summary := fmt.Sprintf("[%s] 执行汇总 - 命令: %s, Root权限: %t, 总数: %d, 成功: %d, 失败: %d\n",
		time.Now().Format("2006-01-02 15:04:05"), command, useRoot, len(results), len(results)-failedCount, failedCount)
	_, err := rct.LogFile.WriteString(summary)
	if err != nil {
		log.Printf("写入汇总日志失败: %v", err)
	}

	// 按主机分组记录详细输出
	hostMap := make(map[string][]TaskResult)
	for _, r := range results {
		hostMap[r.IP] = append(hostMap[r.IP], r)
	}

	for ip, resList := range hostMap {
		entry := fmt.Sprintf("  主机 %s:\n", ip)
		_, err := rct.LogFile.WriteString(entry)
		if err != nil {
			log.Printf("写入汇总日志失败: %v", err)
		}
		for _, r := range resList {
			status := "成功"
			if !r.Success {
				status = "失败"
			}

			if len(r.Error) == 0 {
				detail := fmt.Sprintf("    [%s] 状态: %s | 输出:\n %s \n\n",
					r.Timestamp, status, r.Output)
				_, err := rct.LogFile.WriteString(detail)
				if err != nil {
					log.Printf("写入汇总日志失败: %v", err)
				}
			} else {
				detail := fmt.Sprintf("    [%s] 状态: %s | 输出:\n %s | 错误:\n %s\n\n",
					r.Timestamp, status, r.Output, r.Error)
				_, err := rct.LogFile.WriteString(detail)
				if err != nil {
					log.Printf("写入汇总日志失败: %v", err)
				}
			}
			
			
		}
	}

	if failedCount > 0 {
		_, err = rct.LogFile.WriteString("失败详情:\n")
		if err != nil {
			log.Printf("写入汇总日志失败: %v", err)
		}
		for _, result := range results {
			if !result.Success {
				failDetail := fmt.Sprintf("  IP: %s | 错误: %s\n", result.IP, result.Error)
				_, err = rct.LogFile.WriteString(failDetail)
				if err != nil {
					log.Printf("写入汇总日志失败: %v", err)
				}
			}
		}
	}
	rct.LogFile.Sync()
}

// PrintResults 打印执行结果
func (rct *RemoteControlTool) PrintResults(results []TaskResult) {
	if len(results) == 0 {
		fmt.Println("没有执行结果")
		return
	}

	fmt.Println("\n执行结果汇总:")
	fmt.Println(strings.Repeat("=", 80))

	failedCount := 0
	for _, result := range results {
		status := "成功"
		if !result.Success {
			status = "失败"
			failedCount++
		}

		fmt.Printf("IP: %-15s | 状态: %-6s | 时间: %s\n", result.IP, status, result.Timestamp)
		if !result.Success {
			fmt.Printf("  错误: %s\n", result.Error)
		}
		if result.Output != "" {
			fmt.Printf("  输出:\n    %s\n", strings.ReplaceAll(strings.TrimSpace(result.Output), "\n", "\n    "))
		}
		fmt.Println(strings.Repeat("-", 50))
	}

	fmt.Printf("\n总执行数: %d | 成功: %d | 失败: %d\n",
		len(results), len(results)-failedCount, failedCount)

	if failedCount > 0 {
		fmt.Println("\n失败的IP:")
		for _, result := range results {
			if !result.Success {
				fmt.Printf("  - %s\n", result.IP)
			}
		}
	}
}

// PrintMultipleResults 打印多个命令的执行结果
func (rct *RemoteControlTool) PrintMultipleResults(allResults [][]TaskResult, commands []string) {
	if len(allResults) == 0 {
		fmt.Println("没有执行结果")
		return
	}

	fmt.Println("\n多命令执行结果汇总 (按主机):")
	fmt.Println(strings.Repeat("=", 80))

	hostResults := make(map[string][]TaskResult)
	for _, results := range allResults {
		for _, result := range results {
			hostResults[result.IP] = append(hostResults[result.IP], result)
		}
	}

	for _, hostIP := range getSortedKeys(hostResults) {
		results := hostResults[hostIP]
		fmt.Printf("主机: %s\n", hostIP)
		fmt.Println(strings.Repeat("-", 50))

		hostFailedCount := 0
		for _, result := range results {
			status := "成功"
			if !result.Success {
				status = "失败"
				hostFailedCount++
			}
			fmt.Printf("  命令: %s\n", result.Command)
			fmt.Printf("    状态: %-6s | 时间: %s\n", status, result.Timestamp)
			if !result.Success {
				fmt.Printf("    错误: %s\n", result.Error)
			}
			if result.Output != "" {
				fmt.Printf("    输出:\n      %s\n", strings.ReplaceAll(strings.TrimSpace(result.Output), "\n", "\n      "))
			}
			fmt.Println("    " + strings.Repeat("-", 30))
		}

		fmt.Printf("主机 '%s' 执行汇总: 命令数: %d | 成功: %d | 失败: %d\n",
			hostIP, len(results), len(results)-hostFailedCount, hostFailedCount)
		fmt.Println(strings.Repeat("=", 80))
	}

	totalExecuted := 0
	totalSuccess := 0
	totalFailed := 0
	for _, results := range allResults {
		totalExecuted += len(results)
		for _, result := range results {
			if result.Success {
				totalSuccess++
			} else {
				totalFailed++
			}
		}
	}

	fmt.Printf("\n总体执行汇总: 总数: %d | 成功: %d | 失败: %d\n",
		totalExecuted, totalSuccess, totalFailed)

	if totalFailed > 0 {
		fmt.Println("\n失败的IP:")
		failedIPs := make(map[string]bool)
		for _, results := range allResults {
			for _, result := range results {
				if !result.Success {
					failedIPs[result.IP] = true
				}
			}
		}
		for ip := range failedIPs {
			fmt.Printf("  - %s\n", ip)
		}
	}
}

// getSortedKeys 获取排序后的键
func getSortedKeys(m map[string][]TaskResult) []string {
	var keys []string
	for k := range m {
		keys = append(keys, k)
	}
	for i := 0; i < len(keys); i++ {
		for j := i + 1; j < len(keys); j++ {
			if keys[i] > keys[j] {
				keys[i], keys[j] = keys[j], keys[i]
			}
		}
	}
	return keys
}


